package com.esun.cheetah.view.personal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;

import com.esun.cheetah.biz.personal.attention.AddAttenTeam;
import com.esun.cheetah.biz.personal.attention.AddAttentionMatch;
import com.esun.cheetah.biz.personal.attention.AttentionListManager;
import com.esun.cheetah.biz.personal.attention.CancelAttenMatch;
import com.esun.cheetah.biz.personal.attention.CancelAttenTeam;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.BizCode;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.IntentKey;
import com.esun.cheetah.config.Key;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.model.personal.attention.EventChildInfo;
import com.esun.cheetah.model.personal.attention.EventGroupInfo;
import com.esun.cheetah.network.AbsInferiorityCommunicater;
import com.esun.cheetah.view.custom.CustomProgressDialog;
import com.esun.cheetah.view.match.matchinfo.MatchInfoAct;
import com.esun.util.Tools;

public class EventDetails extends Activity {
	private TextView tvTeamName;
	private String teamName;
	private String teamId;
	private ExpandableListView elistView;
	private Button btnBack;
	private List<EventChildInfo> listTeamRecentRecord;
	private List<List<EventChildInfo>> llTeamR = new ArrayList<List<EventChildInfo>>();
	private List<EventGroupInfo> lEGroup = new ArrayList<EventGroupInfo>();
	/** 添加关注球队 */
	private ImageView ivAtten;
	private String league;
	private static EventChildInfo eventChildInfo;
	private CustomProgressDialog progress;
	private static ImageButton imAddAtten;
	/** 是否关注过该球队 */
	private String isGuan = "";
	/** 赛事handler */
	Handler recentRecordHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			case Config.RECENT_RECORD_SUCESSFUL:
				progressDiss();
				elistView.setAdapter(new EventAdapter(llTeamR, lEGroup));
				elistView.expandGroup(0);
				break;
			case Config.NOT_ATTEN_TEAM:
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				progressDiss();
				Tools.TipNetworkError(EventDetails.this, Language.INTERNET_FAIL);
				break;
			case Config.ATTEN_TEAM:
				ivAtten.setPressed(true);
				break;
			default:
				break;
			}
		}
	};
	/** 取消关注球队handler */
	Handler cancelHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				Toast.makeText(EventDetails.this, "取消关注球队成功", Toast.LENGTH_LONG)
						.show();
				isGuan = "0";
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				if (!Tools.networkStatus(EventDetails.this)) {
					Tools.TipNetworkError(EventDetails.this,
							Language.INTERNET_FAIL);
				}
				break;
			default:
				break;
			}
		}
	};
	/** 添加关注比赛handler */
	Handler addUserMatchHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			case Config.COMMON_INFO_MSG_20001:
				eventChildInfo.setIsguanzhu("1");
				AttentionListManager.getInstance()
						.setAttentionListChanged(true);
				Toast.makeText(EventDetails.this, "添加关注比赛成功", Toast.LENGTH_LONG)
						.show();
				imAddAtten.setImageResource(R.drawable.icon_default_star_add);
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				if (!Tools.networkStatus(EventDetails.this)) {
					Tools.TipNetworkError(EventDetails.this,
							Language.INTERNET_FAIL);
				}
				break;
			default:
				break;
			}
		}
	};

	/** 取消关注比赛handler */
	Handler cancelAtetenMatch = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				// MatchListManager.getInstance().updateAttentionState(eventChildInfo.getFid(),
				// false);
				AttentionListManager.getInstance().updateCancelAttention(
						eventChildInfo.getFid());
				Toast.makeText(EventDetails.this, "取消关注比赛成功", Toast.LENGTH_LONG)
						.show();
				imAddAtten.setImageResource(R.drawable.icon_default_star_);
				eventChildInfo.setIsguanzhu("0");
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				if (!Tools.networkStatus(EventDetails.this)) {
					Tools.TipNetworkError(EventDetails.this,
							Language.INTERNET_FAIL);
				}
				break;
			default:
				break;
			}
		}
	};
	/** 添加球队handler */
	Handler addSearhTeamHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				Toast.makeText(EventDetails.this, "添加球队成功", Toast.LENGTH_LONG)
						.show();
				isGuan = "1";
				ivAtten.setPressed(true);
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				if (!Tools.networkStatus(EventDetails.this)) {
					Tools.TipNetworkError(EventDetails.this,
							Language.INTERNET_FAIL);
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.event_details);
		Intent intent = getIntent();
		teamName = intent.getExtras().getString(Config.TEAM_NAME);
		teamId = intent.getExtras().getString(Config.TEAM_ID);
		league = intent.getExtras().getString(Config.TEAM_LEAGUE);
		inintViews();
	}

	private void inintViews() {
		progress = new CustomProgressDialog(EventDetails.this);
		progress.setMessage("加载数据中...");
		progress.show();
		ivAtten = (ImageView) findViewById(R.id.imAtten);
		ivAtten.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isGuan.equals("0")) {
					new AddAttenTeam(addSearhTeamHandler, teamName, league,
							teamId).startCommunicate();
				}
				if (!isGuan.equals("0")) {
					new CancelAttenTeam(cancelHandler, teamId)
							.startCommunicate();
				}
			}
		});
		elistView = (ExpandableListView) findViewById(R.id.exListView);
		btnBack = (Button) findViewById(R.id.btBack);
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tvTeamName = (TextView) findViewById(R.id.tvTeamName);
		tvTeamName.setText(teamName);
		new RecentRecord(recentRecordHandler, "zq", teamId, UserInfo
				.getUserInfo().getUserName()).startCommunicate();
		elistView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				EventAdapter eventAdapter = (EventAdapter) parent
						.getExpandableListAdapter();
				EventChildInfo eventChildInfo = (EventChildInfo) eventAdapter
						.getChild(groupPosition, childPosition);
				if (eventChildInfo != null) {
					String fid = eventChildInfo.getFid();
					Intent intent = new Intent(EventDetails.this,
							MatchInfoAct.class);
					intent.putExtra(IntentKey.INTENT_KEY_MATCH_ID, fid);
					startActivity(intent);
				}

				return false;
			}
		});
	}

	public class RecentRecord extends AbsInferiorityCommunicater {
		private String teamid;
		private String lot;
		private String userName;

		public RecentRecord(Handler handler, String lot, String teamid,
				String userName) {
			super(handler);
			this.lot = lot;
			this.teamid = teamid;
			this.userName = userName;
		}

		@Override
		public HashMap<String, String> comHashMap() {
			HashMap<String, String> recentRecordMap = new HashMap<String, String>();
			recentRecordMap.put(Key.KEY_ID, BizCode.RECENT_RECOND_ID);
			recentRecordMap.put(Key.TEAM_ID, teamid);
			recentRecordMap.put(Key.KEY_LOT, lot);
			recentRecordMap.put(Key.KEY_USERNAME, userName);
			return recentRecordMap;
		}

		@Override
		public void getJsonContent(String serverRes) throws JSONException {
			JSONObject object = (JSONObject) new JSONTokener(serverRes)
					.nextValue();
			JSONObject object1 = object.getJSONObject("data");
			for (@SuppressWarnings("rawtypes")
			Iterator iter = object1.keys(); iter.hasNext();) {
				String str = (String) iter.next();
				if (str.equals("isguanzhu")) {
					isGuan = object1.getString("isguanzhu");
					if (isGuan.equals("0")) {
						recentRecordHandler
								.sendEmptyMessage(Config.NOT_ATTEN_TEAM);
					}
					if (!isGuan.equals("0")) {
						recentRecordHandler.sendEmptyMessage(Config.ATTEN_TEAM);
					}
				}
			}
			JSONArray jsonArray2 = object1.names();
			for (int i = 0; i < jsonArray2.length(); i++) {
				String arrayKey = jsonArray2.getString(i);
				if (arrayKey.equals("isguanzhu")) {
					continue;
				}
				EventGroupInfo eventGroupInfo = new EventGroupInfo();
				JSONArray jsonArray3 = object1.getJSONArray(arrayKey);
				eventGroupInfo.setAccount("近" + jsonArray3.length() + "场比赛");
				eventGroupInfo.setEvent(arrayKey);
				lEGroup.add(eventGroupInfo);
				listTeamRecentRecord = new ArrayList<EventChildInfo>();
				if (arrayKey.equals("以往赛事参考")) {
					for (int k = 0; k < jsonArray3.length(); k++) {
						EventChildInfo tr = new EventChildInfo();
						JSONObject jsonobject = jsonArray3.getJSONObject(k);
						tr.setLeague(jsonobject.getString("league"));
						tr.setDate(jsonobject.getString("date"));
						tr.setHome(jsonobject.getString("home"));
						tr.setAway(jsonobject.getString("away"));
						tr.setFid(jsonobject.getString("fid"));
						tr.setIsguanzhu(jsonobject.getString("isguanzhu"));
						String score = jsonobject.getString("score");
						String[] scores = score.split(":");
						tr.setHomeCore(scores[0]);
						tr.setAwayCore(scores[1]);
						tr.setHandi(jsonobject.getString("handi"));
						listTeamRecentRecord.add(tr);
					}
					llTeamR.add(listTeamRecentRecord);
				}
				if (arrayKey.equals("未来赛事")) {
					for (int k = 0; k < jsonArray3.length(); k++) {
						EventChildInfo tr = new EventChildInfo();
						JSONObject jsonobject = jsonArray3.getJSONObject(k);
						tr.setLeague(jsonobject.getString("league"));
						tr.setFid(jsonobject.getString("fid"));
						tr.setIsguanzhu(jsonobject.getString("isguanzhu"));
						tr.setDate(jsonobject.getString("date"));
						tr.setHome(jsonobject.getString("home"));
						tr.setAway(jsonobject.getString("away"));
						tr.setDiffer(jsonobject.getString("differ"));
						listTeamRecentRecord.add(tr);
					}
					llTeamR.add(listTeamRecentRecord);
				}
			}
			recentRecordHandler
					.sendEmptyMessage(Config.RECENT_RECORD_SUCESSFUL);
		}
	}

	/**
	 * 近期战绩的Adapter com.esun.cheetah.view.personal.RecentRecordAdapter
	 * 
	 * @author 任付江 create at 2012-4-25 下午6:11:51
	 */
	public class EventAdapter extends BaseExpandableListAdapter {
		private List<List<EventChildInfo>> llTeamR;
		private List<EventGroupInfo> lEGroup;

		public EventAdapter(List<List<EventChildInfo>> llTeamR,
				List<EventGroupInfo> lEGroup) {
			this.llTeamR = llTeamR;
			this.lEGroup = lEGroup;
		}

		@Override
		public int getGroupCount() {
			return lEGroup.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			List<EventChildInfo> listEvent = llTeamR.get(groupPosition);
			int count = llTeamR.get(groupPosition).size();
			if (listEvent != null && count > 0) {
				return count;
			} else {
				return 1;
			}
		}

		@Override
		public Object getGroup(int groupPosition) {
			if (getGroupCount() > 0) {
				return lEGroup.get(groupPosition);
			} else {
				return null;
			}

		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			List<EventChildInfo> listEvent = llTeamR.get(groupPosition);
			int count = llTeamR.get(groupPosition).size();
			if (listEvent != null && count > 0) {
				return llTeamR.get(groupPosition).get(childPosition);
			} else {
				return null;
			}

		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = li.inflate(R.layout.event_group_item, null);
			ImageView iv = (ImageView) convertView
					.findViewById(R.id.imGroupPromp);
			TextView tvEvent = (TextView) convertView
					.findViewById(R.id.tvEvent);
			TextView tvAccount = (TextView) convertView
					.findViewById(R.id.tvAccount);
			tvEvent.setText(lEGroup.get(groupPosition).getEvent());
			tvAccount.setText(lEGroup.get(groupPosition).getAccount());
			if (isExpanded) {
				iv.setBackgroundResource(R.drawable.icon_default_unfold);
			} else {
				iv.setBackgroundResource(R.drawable.icon_default_packup);
			}
			return convertView;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = li.inflate(R.layout.event_child_item, null);
			TextView tvLeagueName = (TextView) convertView
					.findViewById(R.id.tvLeagueName);
			TextView tvHostteam = (TextView) convertView
					.findViewById(R.id.tvHostteam);
			TextView tvHostScore = (TextView) convertView
					.findViewById(R.id.tvHostScore);
			TextView tvWayTeam = (TextView) convertView
					.findViewById(R.id.tvWayTeam);
			TextView tvWayScore = (TextView) convertView
					.findViewById(R.id.tvWayScore);
			TextView tvMatchTime = (TextView) convertView
					.findViewById(R.id.tvMatchTime);
			TextView tvHandi = (TextView) convertView
					.findViewById(R.id.tvHandi);
			if (llTeamR.get(groupPosition) != null
					&& llTeamR.get(groupPosition).size() != 0) {
				ImageButton imbtIsAttention = (ImageButton) convertView
						.findViewById(R.id.imbtIsAttMatch);
				EventChildInfo eventChildInfo = llTeamR.get(groupPosition).get(
						childPosition);
				String differ = eventChildInfo.getDiffer();
				String isAtt = eventChildInfo.getIsguanzhu();
				String wayScore = eventChildInfo.getAwayCore();
				String hostScore = eventChildInfo.getHomeCore();
				if (Integer.valueOf(isAtt) == 1) {
					imbtIsAttention.setBackgroundDrawable(getBaseContext()
							.getResources().getDrawable(
									R.drawable.icon_default_star_add));
				}
				if (differ == null) {
					tvHandi.setText("　已结束");
				} else {
					tvHandi.setText("离比赛" + differ + "天");

				}
				if (wayScore == null) {
					tvWayScore.setText("");
					tvWayScore.setBackgroundDrawable(getBaseContext()
							.getResources().getDrawable(
									R.drawable.img_default_score_soon));
				} else {
					tvWayScore.setText(wayScore);
				}
				if (hostScore == null) {
					tvHostScore.setText("");
					tvHostScore.setBackgroundDrawable(getBaseContext()
							.getResources().getDrawable(
									R.drawable.img_default_score_soon));
				} else {
					tvHostScore.setText(hostScore);
				}
				tvMatchTime.setText(eventChildInfo.getDate());
				tvWayTeam.setText(eventChildInfo.getAway());
				tvHostteam.setText(eventChildInfo.getHome());
				tvLeagueName.setText(eventChildInfo.getLeague());
				imbtIsAttention
						.setOnClickListener(new IsGuanZhu(eventChildInfo));
			} else {
				RelativeLayout llytNomatch = (RelativeLayout) convertView
						.findViewById(R.id.rlytNoMatch);
				TextView tvNomatch = (TextView) convertView
						.findViewById(R.id.tvNoMatch);
				llytNomatch.setVisibility(View.GONE);
				tvNomatch.setVisibility(View.VISIBLE);
			}
			return convertView;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}

	// 目的每次的对象不同,这样就是点击不同item的时候就是不通的实例
	public class IsGuanZhu implements View.OnClickListener {
		private EventChildInfo eventChildInfo2;

		public IsGuanZhu(EventChildInfo eventChildInfo3) {
			this.eventChildInfo2 = eventChildInfo3;
		}

		@Override
		public void onClick(View v) {
			eventChildInfo = eventChildInfo2;
			imAddAtten = (ImageButton) v;
			if (eventChildInfo.getIsguanzhu().equals("1")) {

				// AttentionListManager.getInstance().setAttentionListAdded(false);
				new CancelAttenMatch(cancelAtetenMatch, eventChildInfo.getFid())
						.startCommunicate();
			} else {
				new AddAttentionMatch(addUserMatchHandler, UserInfo
						.getUserInfo().getUserName(), Key.ZQ,
						eventChildInfo.getFid(), eventChildInfo.getHome(),//
						eventChildInfo.getAway(), eventChildInfo.getDate())
						.startCommunicate();
			}

		}

	}

	public void progressDiss() {
		if (progress.isShowing()) {
			progress.dismiss();
		}
	}
}
